#!/bin/bash
THIS_PATH=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

function print_help() {
echo -e "\033[33m\033[1m"
cat <<EOF
[usage] $0  [-r <ros_distro>] [-h]
<ros_distro>: ros distribution name, like "melodic","noetic"...
EOF
echo -e "\033[0m"
}

# 设置默认参数
LOCAL_ARCH=amd64
ROS_DISTRO=noetic
while getopts "p:r:h" OPTNAME
do
  case "${OPTNAME}" in
    "r")
      ROS_DISTRO=${OPTARG}
      ;;
    "h")
      print_help
      exit
      ;; 
    "?")
      echo "UnKnown Option ${OPTARG}"
      print_help
      ;;
    ":")
      echo "No argument value for option ${OPTARG}"
      print_help
      ;;
    "*")
      echo "UnKnown error while processing options"
      print_help
      ;;
  esac
done
echo "build for ${LOCAL_ARCH} >>> ROS DISTRO: ${ROS_DISTRO}"

###########################################################
# 编译设置
BUILD_RELEASE=yes   # yes/no
BUILD_PLATFORM=0    # 0:linux-amd64 1:linux-arm64 2:windows-x64
BUILD_COLCON=no     # yes/no 
BUILD_TYPE=0        # 0:ROS 1:non-ROS

###########################################################
# 设置环境变量
cd $THIS_PATH
export WS_ROOT=$THIS_PATH
# export ROS_DISTRO=$BUILD_ROS
export PROTOC_INSTALL_PATH=/usr/bin
echo ">>> Build workspace in ROS environment."
echo "ROS DISTRO: ${ROS_DISTRO}"

# 配置运行环境
source /opt/ros/${ROS_DISTRO}/setup.bash
source $WS_ROOT/environ/envsetup.sh
zbuild_setup $BUILD_PLATFORM $BUILD_RELEASE $BUILD_TYPE
export WS_OUTPUT=$WS_ROOT/ws_output/$ZBUILD_PLATFORM

# 编译及安装目录创建
mkdir -p $WS_OUTPUT
BUILD_PATH=$WS_OUTPUT/build
DEVEL_PATH=$WS_OUTPUT/devel
INSTALL_PATH=$WS_OUTPUT/install
rm -rf $BUILD_PATH $DEVEL_PATH $INSTALL_PATH

# 要编译的Packages:
PACKAGES="scripts third_party appkit demos"

CMAKE_ARGS="-DCMAKE_VERBOSE_MAKEFILE=ON"
# 开始编译
if [ ${BUILD_COLCON} = "yes" ];then
    export WS_ROSBUILD="colcon"
    COLCON_ARGS="--build-base=$BUILD_PATH --install-base=$INSTALL_PATH --merge-install \
        --cmake-force-configure --cmake-args ${CMAKE_ARGS}"
    colcon build $COLCON_ARGS --packages-select ${PACKAGES}
else
    # catkin config --build-space $BUILD_PATH --devel-space $DEVEL_PATH \
	#     --install-space $INSTALL_PATH --merge --install
    # catkin build -j4 ${PACKAGES} --cmake-args ${CMAKE_ARGS}
    catkin_make_isolated --build-space $BUILD_PATH --devel-space $DEVEL_PATH \
	    --install-space $INSTALL_PATH --merge --install --pkg ${PACKAGES} --cmake-args ${CMAKE_ARGS}
fi

# 目标打包
echo "=============================================================="
cd ${WS_OUTPUT}
rm -rf ${INSTALL_PATH}/include
rm -rf ${INSTALL_PATH}/lib/lib*.a
tar zcf install.tar.gz install
cd ${WS_ROOT}
date
echo "build ok --> ${WS_OUTPUT}"
echo "=============================================================="